import { Button, Space, Toast, Form, DotLoading, AutoCenter } from "antd-mobile";
import { appNavigate, appTypeCheck, checkENV, checkENV2, isMobile, isWechat, } from "@/utils";
import requewt from "@/utils/requewt";
import { API, REDIRECT_TITLE, REDIRECT_WX_COVER, REDIRECT_DESC, REDIRECT_WX_URL, BASE_PATH } from "@/config";
import { useEffect, useLayoutEffect, useReducer, useRef, useState } from "react";
import callFeedback from "@/components/common/modalFeedback";
import { KvHeaderComp, KvContentComp, KvBrandComp } from "@/components/common";
import Router, { useRouter } from "next/router";
import { signIn, signOut } from "next-auth/react";
import { useCookies } from "react-cookie";
import * as gtag from '@/libs/gtag'
import useRecord from "@/components/pages/stores/useRecord";
// import useApp from "@/stores/useApp";
import { useSearchParams } from "next/navigation";
import { motion } from 'framer-motion'
import GameLayout from "@/components/pages/game/gameLayout";
import SharePageImg from "@/components/pages/game/components/share";
import { useCommonHandler } from "@/components/common/hooks";

const pageName = "home";
const klassName = pageName.replace(/\./g, '-');

const LANDING_URL = `/landing`;
const TEST_TOKEN = `user:token:app:7501796:uni-e2d78da298f8131ca16dc0a0cd97885a`

const ENV_MAP = {
  mini: {
    title: `小程序`,
    key: `mini`
  },
  app: {
    title: `APP`,
    key: `app`
  },
  test: {
    title: `测试`,
    key: `test`
  }
}

export default function Page(props) {
  console.log(props, 'props')
  const [env, setENV] = useState(undefined);
  const [loading, setLoading] = useState(true);
  const [cookies, setCookie] = useCookies(['name']);
  const [error, setError] = useState(undefined);
  const [envName, setENVName] = useState(undefined);
  const [showTest, setShowTest] = useState(false);
  const [code, setCode] = useState('')
  // const updateENV = useApp(state => state.updateENV);
  const [qrCode, setQrCode] = useState('')
  const { handleShowShare } = useCommonHandler()
  let timer, flag = 0;
  useEffect(() => {

    // console.log(isMobile(), isWechat(), 'wechat')
    if (!isWechat() || !isMobile()) {
      console.log('app')
      return callFeedback({
        title: '提示',
        content: <div style={{ textAlign: 'center', marginTop: '40px' }}>请在手机端正常进入游戏</div>,
        hideClose: true,
        closeOnAction: false,
        closeOnMaskClick: false,
        actions: <></>
      })
    }
    if (sessionStorage.getItem('auth')) {
      Router.push(LANDING_URL)
      return
    }
    let code = ''
    if (URLSearchParams) {
      const searchParams = new URLSearchParams(global.location.search)
      code = searchParams.get('code')
    } else {
      const searchParams = {}
      const search = global.location.search.split('?')[1]
      const arr = search.split('&')
      arr.forEach((item) => {
        const [key, value] = item.split('=')
        searchParams[key] = value
      })
      code = searchParams.code
    }

    // if (cookies.auth) {
    //   Router.push(LANDING_URL)
    // } else {
    //   // debugge


    // }
    if (code) {
      setCode(code)
      compHandler.login({ code })
      console.log('code')
      global.history.pushState(null, null, global.location.origin + global.location.pathname)
      return
    } else {
      const { origin } = location
      location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${process.env.NEXT_PUBLIC_WX_AUTH_APPID}&redirect_uri=${encodeURIComponent(`${origin}${process.env.NEXT_PUBLIC_BASE_PATH}`)}&response_type=code&scope=snsapi_userinfo#wechat_redirect`
      // global.location.assign()
    }


  }, [])
  const compHandler = {
    login: async (body) => {
      if (!body || !body.code) {
        return
      }
      const options = {
        method: `POST`,
        headers: { "Content-Type": "multipart/form-data" },
        body
      }

      const resp = await requewt(API.user.login, options);
      // const resp = {
      //   data: {
      //     qrcode: 'https://wework.qpic.cn/wwpic/567378_j1A123rdQIueZVB_1695390320/0'
      //   },
      //   error_code: '1001'
      // }
      if (resp.error_code === '1001') {
        return handleShowShare(resp.data?.qrcode)
      }
      if (resp?.error_code !== 0 || resp?.msg !== `ok`) {

        callFeedback({
          bodyClassName: `act-feedback-modal  close-at-center-bottom`,
          title: <div dangerouslySetInnerHTML={{ __html: resp?.msg || `登入失败!` }}>
          </div>,
          hideClose: true,
          actions: [
            // <Button key={`close`} onClick={e => {
            //   if(env === `mini`){
            //     wx?.miniProgram?.navigateBack()
            //   }
            //   else if(env === `app`) {
            //     window.UNIApp?.closePage()
            //   }
            // }} size="small"
            //         className="act-btn act-btn-primary">确认</Button>
          ]
        })
        return null
      }
      const { token } = resp?.data;
      await setCookie('auth', token, { path: `/`, maxAge: 3600 * 24 * 7 });
      // setCookie('auth', token);
      sessionStorage.setItem('auth', token)
      const resolve = await signIn("credentials", { token, redirect: false });
      console.log(`resolve`, resolve)

      await Router.replace(LANDING_URL);
    },
    testing: async () => {
      const token = await compHandler.login({
        code
      })
      if (!token) return
      await setCookie('auth', token);
      // await setCookie('auth', token, {path: `/`, maxAge: 3600 * 24 * 7});

      const resolve = await signIn("credentials", { token, redirect: false });

      await Router.replace(LANDING_URL)
    },
    logout: async () => {
      requewt(API.user.logout).then(() => {
        signOut()
        Toast.show('登出成功')

        // setCookie
      })
    }
  }

  useEffect(() => {
    (async () => {
      setLoading(true);
      // await waitForAuth('mini');

    })()
  }, [])

  // useEffect(() => {
  //   if (!ENV_MAP[env]) return setError(`请在引力域小程序或APP内打开!`);
  //   else setError(undefined);
  //   useMap[env].auth();
  //   updateENV(env);
  //   setENVName(ENV_MAP[env].title);

  //   if (env === `mini`) {
  //     const data = {
  //       title: REDIRECT_TITLE, // 分享标题
  //       desc: REDIRECT_DESC,
  //       path: `/pagesPublic/h5/detailH5?jumpDataVale=${encodeURIComponent(REDIRECT_WX_URL)}`,
  //       imageUrl: REDIRECT_WX_COVER
  //     }
  //     // alert(JSON.stringify(data))
  //     wx?.miniProgram.postMessage({data})
  //   }
  // }, [])

  const useMap = {
    mini: {
      auth: async e => {
        let { token: uni_token, source, position } = Router.query || {};
        if (!uni_token) {
          if (process.env.NODE_ENV === 'development') uni_token = TEST_TOKEN
          else return wx.miniProgram.navigateTo({ url: `/pages/user/auth` });
        }

        gtag.event({
          action: 'mini_login',
          category: 'Login',
          label: `${position}`,
        })

        const values = { code, position };
        await compHandler.login(values, async () => {
          await Router.replace(LANDING_URL)
        });
      }
    },
    app: {
      auth: async e => {
        const { position } = Router.query || {};
        const uni_token = window.UNIApp?.getToken();
        if (!uni_token) return window.UNIApp?.loginApp('logincallback');

        gtag.event({
          action: 'app_login',
          category: 'Login',
          label: `${position}`,
        })

        const values = { UNIAuth: uni_token, source: `app`, position }
        await compHandler.login(values, async () => {
          // window.backEventCallback = function () {
          //   alert("trgger callback");
          //   window.location.href = `/basketball716`;
          // }
          // window.UNIApp?.setBackEvent(function() {
          //     alert("trgger callback");
          //     window.location.href = `/basketball716`;
          // });
          await Router.replace(LANDING_URL)
        });
      }
    },
    test: {
      auth: async e => {
        const { position } = Router.query || {};
        const values = { UNIAuth: TEST_TOKEN, source: `test`, position }

        gtag.event({
          action: 'test_login',
          category: 'Login',
          label: `${position}`,
        })

        await compHandler.login(values, async () => {
          await Router.replace(LANDING_URL)
        });
      }
    }
  }

  const wait4Auth = async (ev) => {
    const resp = await checkENV2();
    // updateENV(resp);
    setENV(resp)
  }

  const waitForAuth = async (ev) => {
    if (flag >= 30) {
      setLoading(false);
      setShowTest(`未检测到正式环境`);
      // Toast.show({duration: 3000, content: `授权失败！请保证网络畅通、并在引力域的APP或小程序中打开`});
      return
    }
    setTimeout(() => {
      if (ev) {
        setENV(ev);
        setLoading(false);
        return;
      }
      flag++;
      const resolve = checkENV();
      // console.log(`resolve`, resolve)
      waitForAuth(resolve);
    }, 100);
  };

  return (
    <>
      <div className="inner page">
        {/* <motion.div>
                <motion.img 
                    width='100%'
                    // style={{margin: '6vh 0'}}
                    className="idd-img"
                    src={`${BASE_PATH}/img/game/idd.png`}
                />
            </motion.div> */}
        {/* <SharePageImg /> */}

        {/* {children} */}
        {/* <AutoCenter>
          <img
            src={qrCode}

            width={120}
            height={120}
          />
        </AutoCenter>
        <div style={{ color: '#fff', textAlign: 'center' }}>扫码入群</div>
        <div style={{ color: '#fff', textAlign: 'center' }}>一起 ”趣“ 改智电iDD吧</div> */}

        {/* <GameApp category={'1'} sprites={sprites} car={car} /> */}
      </div>
      {/* */}
      {/* <img src="https://yinli-qixi-run.varwey.com/2023/3w-jump-alien-230703/img/kv/kv-bg-sec.jpg" className="img-hidden" alt="" />

      <audio src="https://yinli-qixi-run.varwey.com/2023/3w-jump-alien-230703/audio/ae-bgm.mp3" /> */}

    </>

  )
}


Page.need2auth = false;
Page.pageName = pageName;